#include "uesrlib.h"

// 低通滤波示例代码
// int main(void) {
//     LowPassFilter myFilter;
//     float alpha = 0.1f;  // 滤波系数，可以根据需要调整

//     LowPassFilter_Init(&myFilter, alpha);

//     float input_values[] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f};
//     float filtered_value;

//     for (int i = 0; i < 5; i++) {
//         filtered_value = LowPassFilter_Update(&myFilter, input_values[i]);
//         // 处理 filtered_value
//     }

//     return 0;
// }

// 初始化低通滤波器
void LowPassFilter_Init(LowPassFilter* filter, float alpha) {
    filter->alpha = alpha;
    filter->prev_output = 0.0f;  // 初始输出设为0
}

// 应用低通滤波器
float LowPassFilter_Update(LowPassFilter* filter, float input) {
    float output = filter->alpha * input + (1.0f - filter->alpha) * filter->prev_output;
    filter->prev_output = output;  // 更新上一次的输出
    return output;
}

// 均值滤波示例代码
int main(void) {
    const int buffer_size = 5;
    float buffer[buffer_size];

    MovingAverageFilter myFilter;
    MovingAverageFilter_Init(&myFilter, buffer, buffer_size);

    float input_values[] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f};
    float filtered_value;

    for (int i = 0; i < 10; i++) {
        filtered_value = MovingAverageFilter_Update(&myFilter, input_values[i]);
        printf("Filtered value: %f\n", filtered_value);
    }

    return 0;
}

// 初始化均值滤波器
void MovingAverageFilter_Init(MovingAverageFilter* filter, float* buffer, int buffer_size) {
    filter->buffer = buffer;
    filter->buffer_size = buffer_size;
    filter->index = 0;
    filter->sum = 0.0f;
    filter->count = 0;

    for (int i = 0; i < buffer_size; i++) {
        filter->buffer[i] = 0.0f;  // 初始化缓冲区为0
    }
}

// 应用均值滤波器
float MovingAverageFilter_Update(MovingAverageFilter* filter, float input) {
    // 如果缓冲区未满，直接累加新值
    if (filter->count < filter->buffer_size) {
        filter->sum += input;
        filter->buffer[filter->index] = input;
        filter->index = (filter->index + 1) % filter->buffer_size;
        filter->count++;
        return filter->sum / filter->count;
    } else {
        // 从sum中减去旧值
        filter->sum -= filter->buffer[filter->index];

        // 将新值存储到缓冲区
        filter->buffer[filter->index] = input;

        // 将新值加到sum中
        filter->sum += input;

        // 更新索引
        filter->index = (filter->index + 1) % filter->buffer_size;

        // 计算并返回均值
        return filter->sum / filter->buffer_size;
    }
}